package com.qf.set.controller;


import com.qf.common.annotation.Log;
import com.qf.common.core.controller.BaseController;
import com.qf.common.core.domain.AjaxResult;
import com.qf.common.core.page.TableDataInfo;
import com.qf.common.enums.BusinessType;
import com.qf.set.domain.TmsEmployee;
import com.qf.set.service.ITmsEmployeeService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/tms/employee")
public class TmsEmployeeController extends BaseController {

    @Autowired
    private ITmsEmployeeService employeeService;

    // @PreAuthorize("@ss.hasPermi('tms:employee:list')")
    @GetMapping("/list")
    public TableDataInfo list(TmsEmployee employee) {
        List<TmsEmployee> list = employeeService.selectEmployeePage(employee);
        return getDataTable(list);
    }

    // @PreAuthorize("@ss.hasPermi('tms:employee:query')")
    @GetMapping("/{employeeId}")
    public AjaxResult getInfo(@PathVariable String employeeId) {
        return AjaxResult.success(employeeService.selectEmployeeById(employeeId));
    }

    // @PreAuthorize("@ss.hasPermi('tms:employee:add')")
    @PostMapping
    @Log(title = "员工管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody TmsEmployee employee) {
        return AjaxResult.success(employeeService.insertEmployee(employee));
    }

    // @PreAuthorize("@ss.hasPermi('tms:employee:edit')")
    @PutMapping
    @Log(title = "员工管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@RequestBody TmsEmployee employee) {
        return AjaxResult.success(employeeService.updateEmployee(employee));
    }

    // @PreAuthorize("@ss.hasPermi('tms:employee:remove')")
    @DeleteMapping("/{employeeIds}")
    @Log(title = "员工管理", businessType = BusinessType.DELETE)
    public AjaxResult remove(@PathVariable String[] employeeIds) {
        return AjaxResult.success(employeeService.deleteEmployeeByIds(employeeIds));
    }

    // @PreAuthorize("@ss.hasPermi('tms:employee:import')")
    @PostMapping("/import")
    @Log(title = "员工管理", businessType = BusinessType.IMPORT)
    public AjaxResult importEmployee(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }

        try {
            // 读取Excel文件
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            
            List<TmsEmployee> employeeList = new ArrayList<>();
            
            // 从第二行开始读取数据（第一行是标题行）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                
                TmsEmployee employee = new TmsEmployee();
                // 根据Excel的列顺序设置员工信息
                // 这里假设Excel的列顺序为：员工账号、员工姓名、部门ID、角色ID、员工状态
                if (row.getCell(0) != null) {
                    employee.setEmployeeAccount(getStringCellValue(row.getCell(0)));
                }
                if (row.getCell(1) != null) {
                    employee.setEmployeeName(getStringCellValue(row.getCell(1)));
                }
                if (row.getCell(2) != null) {
                    employee.setDeptId(getNumericCellValueAsLong(row.getCell(2)));
                }
                if (row.getCell(3) != null) {
                    employee.setRoleId(getNumericCellValueAsInt(row.getCell(3)));
                }
                if (row.getCell(4) != null) {
                    employee.setEmployeeStatus(getStringCellValue(row.getCell(4)));
                }
                
                employeeList.add(employee);
            }
            
            workbook.close();
            
            // 调用服务层进行导入
            int count = employeeService.importEmployees(employeeList);
            
            return AjaxResult.success("导入成功，共导入" + count + "条员工数据");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 安全地获取单元格的字符串值
     */
    private String getStringCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                // 如果是日期格式，可能需要特殊处理
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    // 对于数值类型，检查是否为整数值
                    double numericValue = cell.getNumericCellValue();
                    if (numericValue == Math.floor(numericValue)) {
                        // 如果是整数，直接转换为Long然后再转成字符串，避免小数点
                        return String.valueOf((long) numericValue);
                    } else {
                        // 非整数才保留小数部分
                        return String.valueOf(numericValue);
                    }
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                try {
                    double formulaValue = cell.getNumericCellValue();
                    if (formulaValue == Math.floor(formulaValue)) {
                        return String.valueOf((long) formulaValue);
                    } else {
                        return String.valueOf(formulaValue);
                    }
                } catch (IllegalStateException e) {
                    return cell.getStringCellValue();
                }
            default:
                return "";
        }
    }
    
    /**
     * 安全地获取单元格的数值并转换为Long
     */
    private Long getNumericCellValueAsLong(Cell cell) {
        if (cell == null) {
            return null;
        }
        
        try {
            if (cell.getCellType() == CellType.STRING) {
                // 如果是字符串类型，尝试转换为数字
                return Long.parseLong(cell.getStringCellValue());
            } else {
                // 对于数值类型，直接转换
                return (long) cell.getNumericCellValue();
            }
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 安全地获取单元格的数值并转换为Integer
     */
    private Integer getNumericCellValueAsInt(Cell cell) {
        if (cell == null) {
            return null;
        }
        
        try {
            if (cell.getCellType() == CellType.STRING) {
                // 如果是字符串类型，尝试转换为数字
                return Integer.parseInt(cell.getStringCellValue());
            } else {
                // 对于数值类型，直接转换
                return (int) cell.getNumericCellValue();
            }
        } catch (Exception e) {
            return null;
        }
    }
}